<template>
	<view class="p-1">
		<!-- 主播 -->
		<view class="flex" v-if="room.role==='anchor'">
			<view class="flex flex-1">
				<trtc-local-view :viewId="room.anchor.member.id"
					style="opacity: 0;width: 1px;height: 1px;"></trtc-local-view>
				<view class="flex-col items-center">
					<nv-image :src="room.anchor?.member.headimg" shape="circle" width="100rpx"
						height="100rpx"></nv-image>
					<text class="color-white font-sm">{{room.anchor?.member.nickname}}</text>
				</view>
				<view class="flex-col justify-center flex-1 items-center">
					<nv-image @click="startLocalAudio(params.audio)"
						:src="params.audio?`/static/icons/audio.png`:`/static/icons/audio_.png`" width="60rpx"
						height="60rpx"></nv-image>
				</view>
			</view>
			<!--  -->
			<view class="flex-col items-center" style="width:144rpx">
				<nv-image src="/static/icons/connecting.png" width="48rpx" height="48rpx"></nv-image>
				<view class="" style="margin: 10rpx 0rpx;">

					<text class="color-white">{{userOption.userId?'正在连麦':'等待连麦'}}</text>
				</view>
				<text class="color-gray font-sm">00:00:00</text>
			</view>
			<!--  -->
			<view class="flex-1 flex">
				<trtc-remote-view :viewId="connectingUserId"
					style="opacity: 0;width: 1px;height: 1px;"></trtc-remote-view>
				<view class="flex-col justify-center flex-1 items-center" v-if="connectingUserId">
					<nv-image :src="userOption.audio?`/static/icons/audio.png`:`/static/icons/audio_.png`" width="60rpx"
						height="60rpx"></nv-image>
				</view>
				<view class="flex-col justify-around flex-1 items-center" v-else>
				</view>
				<view class="flex-col items-center" v-if="connectingUserId">
					<nv-image :src="userOption.headimg" v-if="userOption.headimg" shape="circle" width="100rpx"
						height="100rpx"></nv-image>
					<nv-image src="" v-else shape="circle" width="100rpx" height="100rpx"></nv-image>
					<text class="color-white font-sm">{{userOption.nickname}}</text>
				</view>
			</view>
		</view>
		<!-- 用户 -->
		<view class="flex" v-if="room.role==='user'">
			<!-- /////////////////////////////////主播 -->
			<view class="flex-1 flex">

				<trtc-remote-view :viewId="room.anchor?.member.id"
					style="opacity: 0;width: 1px;height: 1px;"></trtc-remote-view>
				<view class="flex-col items-center">
					<nv-image :src="room.anchor?.member.headimg" shape="circle" width="100rpx"
						height="100rpx"></nv-image>
					<text class="color-white font-sm">{{room.anchor?.member.nickname}}</text>
				</view>
				<view class="flex-col justify-center flex-1 items-center">
					<nv-image :src="userOption.audio?`/static/icons/audio.png`:`/static/icons/audio_.png`" width="60rpx"
						height="60rpx"></nv-image>
				</view>
			</view>
			<!--  -->
			<view class="flex-col items-center" style="width:144rpx">
				<nv-image src="/static/icons/connecting.png" width="48rpx" height="48rpx"></nv-image>
				<view class="" style="margin: 10rpx 0rpx;">
					<text class="color-white">{{params.userId?'正在连麦':'等待连麦'}}</text>
				</view>
				<text class="color-gray font-sm">00:00:00</text>
			</view>
			<!--  -->
			<view class="flex flex-1">
				<trtc-local-view :viewId="connectingUserId"
					style="opacity: 0;width: 1px;height: 1px;"></trtc-local-view>
				<view class="flex-col justify-around flex-1 items-center" v-if="connectingUserId">
					<nv-image @click="startLocalAudio(params.audio)"
						:src="params.audio?`/static/icons/audio.png`:`/static/icons/audio_.png`" width="60rpx"
						height="60rpx"></nv-image>

					<uni-icons type="clear" size="40" color="red" v-if="connectingUserId==user.id"
						@click="delConnection({id:connectingId,sts:1})"></uni-icons>
				</view>
				<view class="flex-col justify-around flex-1 items-center" v-else>
				</view>
				<view class="flex-col items-center" v-if="connectingUserId">
					<nv-image :src="params.headimg" v-if="params.headimg" shape="circle" width="100rpx"
						height="100rpx"></nv-image>
					<nv-image src="" v-else shape="circle" width="100rpx" height="100rpx"></nv-image>
					<text class="color-white font-sm">{{params.nickname}}</text>
				</view>
			</view>
		</view>
		<!--  -->
		<view class="">
			<!-- 排队列表 -->
			<uni-popup ref="popupRef" type="bottom" background-color="#fff" borderRadius="10px 10px 0px 0px"
				@change="change">
				<view class="flex-col" style="height: 600rpx;">
					<scroll-view scroll-y="true" class="flex-1" v-if="queueList.length>0">
						<view class="p-2">
							<view class="flex items-center justify-between py-1" v-for="e,i in queueList" :key="i">
								<view class="flex">
									<text class="mr-1">{{i+1}}</text>
									<text>{{e.member.nickname}}</text>
									<text style="margin-left: 20rpx;">{{e.sts!==0?e.sts!==1?'连麦结束':'接麦中':'正在等待'}}</text>
								</view>
								<view class="flex" v-if="room.role=='anchor'">
									<button size="mini" v-if="e.sts==0" @click="userConnection(e)">上麦</button>
									<button size="mini" @click="delConnection(e)">{{e.sts==0?'删除':'结束'}}</button>
								</view>
							</view>
						</view>
					</scroll-view>
					<view class="flex-center flex-1" v-else>
						<text>暂无数据</text>
					</view>
				</view>

			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import liveApi from '@/apis/apiList/liveApi';
	import TrtcCloud from '@/TrtcCloud/lib/index';
	import nvImage from '@/uni_modules/uv-image/components/uv-image/uv-image.vue'
	import {
		TRTCAppScene,
		TRTCRoleType,
		TRTCVideoStreamType
	} from '@/TrtcCloud/lib/TrtcDefines';
	import TrtcLocalView from '@/TrtcCloud/view/TrtcLocalView';
	import TrtcRemoteView from '@/TrtcCloud/view/TrtcRemoteView';
	import {
		nextTick,
		ref
	} from 'vue';
	import userApi from '@/apis/apiList/userApi';
	let trtcCloud = TrtcCloud.createInstance(); //创建实例
	const videoRef = ref(null)
	const popupRef = ref(null)
	const video1Ref = ref()
	const userList = ref([])
	const room = ref({
		role: 'anchor'
	})
	const emit = defineEmits(['createCustomMessage', 'sendMsg'])
	const user = uni.getStorageSync('user')
	const liveOption = ref({})
	const queueList = ref([])
	const connectingId = ref('') //麦序Id
	const connectingUserId = ref('') //连线用户Id
	const params = ref({
		userId: "",
		headimg: '',
		nickname: '',
		live: false,
		audio: false
	})
	const userOption = ref({
		userId: "",
		headimg: '',
		nickname: '',
		live: false,
		audio: false
	})

	const tips = ref([])
	//初始化直播间
	const startLive = (val, options) => {
		room.value = val
		liveOption.value = options
		nextTick(() => {
			// 进入房间
			enterRoom(true)
			// 监听
			onMonitor()
			// 排麦列表
			getLiveRoomVoilist(true)
		})
	}
	// 退出直播间
	const closeLive = () => {
		clearTimeout(VoiTime.value)
		enterRoom(false)
		offMonitor()
	}
	// 排麦列表
	const getLiveRoomVoilist = (type) => {
		liveApi.getLiveRoomVoilist({
			"liveroom.id": room.value.id
		}).then(res => {
			queueList.value = res.data
			queueList.value.forEach(a => {
				if (a.sts == 1) {
					// 连麦中
					userConnection(a, type)
				}
			})
		})
	}
	// 申请排麦
	const connection = () => {
		const params = {
			"liveroom.id": room.value.id,
			"member.id": liveOption.value.userId,
			"anchor.id": room.value.anchor.id,
			"voists": '0'
		}
		liveApi.memberAddVoiOrder(params).then(res => {
			uni.showToast({
				icon: "none",
				title: "排麦成功"
			})
			emit('sendMsg', `${user.nickname}加入了排麦`)
			getLiveRoomVoilist()
			createCustomMessage('getLiveRoomVoilist')
		})

	}
	// 上麦
	const userConnection = (e, type) => {
		console.log(connectingUserId.value);
		if (connectingUserId.value) {
			uni.showToast({
				icon: "none",
				title: '当前有人正在连麦'
			})
			return
		}
		if (!type) emit('sendMsg', `${ e.member.nickname}已上麦`)

		console.log('1111111111111111111111111111111111111重连', e);
		if (e.sts == 1) {
			// 重连
			if (room.value.role == 'user') {
				// 用户设置自己
				// console.log(uni.getStorageSync('user'));
				params.value = {
					userId: e.member.id,
					headimg: e.member.headimg,
					nickname: e.member.nickname,
					live: true,
					audio: true
				}
				connectingId.value = e.id
				connectingUserId.value = e.member.id
				nextTick(() => {
					// startLocalPreview(false)
					startLocalAudio(false)
				})

			} else {
				// 主播设置用户
				userOption.value.userId = e.member.id
				userOption.value.headimg = e.member.headimg
				userOption.value.nickname = e.member.nickname
				const obj = {
					userId: e.member.id,
					available: true
				}
				connectingId.value = e.id
				connectingUserId.value = e.member.id
				if (VoiTime.value == null) memberVoiAnchorAdd()
				nextTick(() => {
					// onUserVideoAvailable(obj)
					onUserAudioAvailable(obj)
				})
			}

		} else if (e.sts === 0) {
			const query = {
				id: e.id,
				"anchor.id": room.value.anchor.id
			}
			liveApi.anchorStartVoiOrder(query).then(res => {
				userOption.value.userId = e.member.id
				const obj = {
					userId: e.member.id,
					available: true
				}
				connectingId.value = e.id
				connectingUserId.value = e.member.id
				getLiveRoomVoilist()
				createCustomMessage('getLiveRoomVoilist')
				if (VoiTime.value == null) memberVoiAnchorAdd()
				nextTick(() => {
					// onUserVideoAvailable(obj)
					onUserAudioAvailable(obj)
				})

			})
		}
	}
	const VoiTime = ref(null)
	// 查询连麦时间
	const memberVoiAnchorAdd = () => {
		liveApi.memberVoiAnchorAdd({
			id: connectingId.value
		}).then(res => {
			if (res.data.sts == 0) {} else if (res.data.sts == 1) {
				uni.showToast({
					icon: 'none',
					title: "剩余时长不足3分钟"
				})
			} else {
				uni.showToast({
					icon: 'none',
					title: "连麦已结束"
				})
				clearTimeout(VoiTime.value)
				VoiTime.value = null
				onRemoteUserLeaveRoom({
					userId: userOption.value.userId,
					reason: false
				})
			}
		})
		VoiTime.value = setTimeout(() => {
			memberVoiAnchorAdd()
		}, 30000)
	}
	// 删除排麦用户
	const delConnection = (val) => {
		console.log(val);
		if (val.sts == 0) {
			// 删除连麦
			anchorDelVoiOrder(val.id)
		}
		if (val.sts == 1) {
			// 结束连麦
			memberVoiAnchorEnd(val.id)
		}
	}
	// 主播关闭连麦
	const anchorDelVoiOrder = (id) => {
		const params = {
			id: id || connectingId.value,
			"anchor.id": room.value.anchor.id
		}
		liveApi.anchorDelVoiOrder(params).then(res => {
			getLiveRoomVoilist()
			createCustomMessage('getLiveRoomVoilist')
		})
	}
	// 主播结束连麦
	const memberVoiAnchorEnd = (id) => {
		liveApi.memberVoiAnchorEnd({
			id: id
		}).then(res => {
			clearTimeout(VoiTime.value)
			getLiveRoomVoilist()
			// createCustomMessage('getLiveRoomVoilist')
			createCustomMessage('break', userOption.value.userId)
			const obj = {
				userId: userOption.value.userId,
				available: false
			}
			nextTick(() => {
				// onUserVideoAvailable(obj)
				if (room.value.role == 'user') trtcCloud.stopLocalAudio()
				onUserAudioAvailable(obj)
			})
			nextTick(() => {
				connectingUserId.value = ""
				userOption.value.userId = ''
			})

		})
	}
	// 进入房间
	const enterRoom = (type) => {
		if (type) {
			trtcCloud.enterRoom(liveOption.value, TRTCAppScene.TRTCAppSceneVideoCall); //进房

			startLocalAudio(false)
		} else {
			trtcCloud.exitRoom() //退房
			uni.navigateBack({
				delta: 1
			})
		}
	}
	// 打开/关闭摄像头
	const startLocalPreview = (type) => {
		// params.value.live = !type
		// if (params.value.live) {
		// 	trtcCloud.startLocalPreview(true, liveOption.value.userId); //摄像头
		// } else {
		// 	trtcCloud.stopLocalPreview() //摄像头
		// }
	}


	// 通知直播间更新排麦列表
	const createCustomMessage = (type, val) => {
		emit('createCustomMessage', {
			data: 'use',
			description: type,
			extension: val || ""
		})
	}
	// 接受操作
	const onUse = (val) => {
		// 刷新排麦列表
		if (val.description == 'getLiveRoomVoilist') getLiveRoomVoilist()
		// 下麦
		if (val.description == 'break') {
			// startLocalPreview(true)
			clearTimeout(VoiTime.value)
			connectingUserId.value = ""
			getLiveRoomVoilist()
			startLocalAudio(true)
			nextTick(() => {
				params.value.userId = ''
			})
		}
	}
	// 进入房间
	const onRemoteUserEnterRoom = (userId) => {
		console.log('进入room', userId);

		// 添加主播视频
		// if (room.value.role === 'user' && userOption.value.userId == '') userOption.value.userId = userId
		// else userOption.value.userId = userId
	}
	// 查询用户信息
	const queryMemberInfo = (id) => {
		return userApi.queryMemberInfo({
			id: id
		})
	}
	// 退出房间
	const onRemoteUserLeaveRoom = (res) => {
		console.log('退出room', res);
		// const {
		// 	userId,
		// 	reason
		// } = res
		// if (userId === userOption.value.userId) userOption.value.userId = ""
		// tips.value.push(`${userId}${reason!==0?reason!==1?'踢出房间':'超时退出':'退出房间'}`)
	}
	// 视频
	const onUserVideoAvailable = (res) => {
		// const {
		// 	userId,
		// 	available
		// } = res;
		// // console.log('live', res);
		// userOption.value.live = available
		// nextTick(() => {
		// 	if (userId && available) {
		// 		trtcCloud.startRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeSmall,
		// 			userId);
		// 		// tips.value.push(`${userId}开启视频`)
		// 	} else {
		// 		trtcCloud.stopRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeSmall);
		// 		// tips.value.push(`${userId}关闭视频`)
		// 	}
		// })
	}
	// 打开/关闭麦克风
	const startLocalAudio = (type) => {
		// if (room.value.role == 'user') {
		// 	if (connectingUserId.value != user.id) return
		// }
		params.value.audio = !type
		console.log(params.value.audio);
		if (params.value.audio) {
			trtcCloud.startLocalAudio(); //麦克风
		} else {
			trtcCloud.stopLocalAudio(); //麦克风
		}
	}
	// 音频
	const onUserAudioAvailable = async (res) => {
		console.log('audio', res);
		// const {
		// 	userId,
		// 	available
		// } = res;

		// if (userId != userOption.value.userId) {
		// 	if (room.value.role != 'user') params.value.audio = available
		// 	else userOption.value.audio = available
		// }
		// trtcCloud.muteRemoteAudio(userId, false);
		// if (userId && available) {
		// console.log(connectingUserId.value);
		// tips.value.push(`${userId}开启声音`)
		// if (room.value.role == 'user') {
		// 	const val = await queryMemberInfo(userId)
		// 	userOption.value.userId = userId
		// 	userOption.value.audio = true
		// 	userOption.value.headimg = val.data.member.headimg
		// 	userOption.value.nickname = val.data.member.nickname
		// }

		// } else {
		// trtcCloud.muteRemoteAudio(userId, true)
		// 当远端用户关闭视频流时，停止订阅
		// tips.value.push(`${userId}关闭声音`)
		// }
		// userOption.value.audio = available
	}
	// 监听
	const onMonitor = () => {
		// 监听房间人员进入
		trtcCloud.on("onRemoteUserEnterRoom", onRemoteUserEnterRoom);
		// 监听房间人员离开
		trtcCloud.on("onRemoteUserLeaveRoom", onRemoteUserLeaveRoom);
		// // 监听房间其他人的视频
		// trtcCloud.on('onUserVideoAvailable', onUserVideoAvailable);
		// 监听房间其他人的音频
		// trtcCloud.on('onUserAudioAvailable', onUserAudioAvailable);
	}
	// 退出监听
	const offMonitor = () => {
		// 监听房间人员进入
		trtcCloud.off("onRemoteUserEnterRoom", onRemoteUserEnterRoom);
		// 监听房间人员离开
		trtcCloud.off("onRemoteUserLeaveRoom", onRemoteUserLeaveRoom);
		// // 监听房间其他人的视频
		// trtcCloud.off('onUserVideoAvailable', onUserVideoAvailable);
		// 监听房间其他人的音频
		// trtcCloud.off('onUserAudioAvailable', onUserAudioAvailable);
	}
	defineExpose({
		startLive,
		closeLive,
		onUse,
		popupRef,
		connection
	})
</script>

<style>
</style>